package ncc.bs.Plugins;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.itf.pub.dbservice.IDBService;
import nc.itf.pub.dbservice.INCPushCZService;
import nc.jdbc.framework.generator.IdGenerator;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDateTime;
import nccloud.bs.log.LogVO;
import nccloud.utils.baseapp.HttpReqUtils;
import nccloud.utils.baseapp.InitParamUtils;
import nccloud.utils.baseapp.ToolUtils;

/** 
 * <p>同步财政系统</p>
  * 辅助核算要素信息
 * @author Administrator
 * @date 2024年2月26日
 */
public class AssistHSYSBackGroundWorkPlugin extends AbstractBackgroundWorkPlugin{
	private BaseDAO dao;
	private final SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
	private final SimpleDateFormat ymdsfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private IDBService dbService;
	private INCPushCZService ncPushCZService;
	
	@SuppressWarnings({ "rawtypes", "unused" })
	@Override
	public void doBusiness(Map keyMap) throws BusinessException {
		List<Map<String, Object>> lists = queryData(buildSQL(keyMap));
		try {
			if(lists == null ) return;
			// 对分组的数据进行推送
			for(Map<String, Object> map : lists) {
				List<LogVO> listVOs = new ArrayList<>();
				String message = null;
				String issuccess = "Y";
				String result = null;
				try {
					JSONArray batparam = buildParam(map,listVOs);
					String param = super.getParam(batparam,"DWKJHS04", super.getAppid()); // 每十行数据合并在一起推送
					if(param == null || "".equals(param)) return;
					if(param == null) return;
					result = HttpReqUtils.sendPost(getURL("DEF001"), param);
					getLog().info("----第四步接口响应结果::" + result);
					JSONObject jsonres = JSONObject.parseObject(result);
					Object code = jsonres.get("code");
					if("200".equals(code)) {
						this.getNcPushCZService().insertFZHSYSVOs(batparam);
						message = "同步成功";
					}else {
						message = jsonres.getString("msg"); 
						issuccess = "N";
						result = jsonres.toString();
					}
					
				}catch(Exception e) {
					message = e.getMessage();
					issuccess = "N";
				}finally {
					for(LogVO vo : listVOs) {
						vo.setIssuccess(issuccess);
						vo.setError(message);
						vo.setVdef2(result);
						vo.setDr("0");
						
					}
					getDbService().insertVOList(listVOs);
				}
			}
		}catch(Exception e) {
			LogVO vo = new LogVO();
			vo.setPk_id(NCLocator.getInstance().lookup(IdGenerator.class).generate());
			vo.setIssuccess("N");
			vo.setPk_group("0001A210000000000JB9");
			vo.setPk_billtypeid("assistHS");
			vo.setSystem_flag("financial");
			vo.setVdef1("拉取参数: 类型"+ keyMap.get("type")+",开始日期:"+keyMap.get("begindate")+"结束日期:"+keyMap.get("enddate")+",同步频率:"+keyMap.get("synctime"));
			vo.setError("辅助核算同步:"+e.getMessage());
			getDbService().insertVO(vo);
		}
	}

	/**
	 * 查询需要同步的数据
	 * @param sql
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>>  queryData(String sql)  throws BusinessException{
		if(sql == null) return null;
		List<Map<String, Object>> lists = (List<Map<String, Object>>)getDao().executeQuery(sql, new MapListProcessor());
		return lists == null ||  lists.isEmpty() ? null : lists;
	}
	
	/**
	 * 构建数据查询sql
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("rawtypes")
	public String buildSQL(Map keyMap) throws BusinessException{
		StringBuilder sb = new StringBuilder();
		if(keyMap != null && !keyMap.isEmpty()) {
			sb.append("select ");
			sb.append("    fz.pk_accassitem data_id, fz.code vbillcode, fz.code element_code, fz.name element_name,fz.refnodename name, ");
			sb.append("    fz.creationtime start_date,fz.modifiedtime update_time,mc.name code, oos.pk_org  pk_org,oos.pk_vid pk_org_v,og.pk_group ,");
			sb.append("    case  fz.dr when 0 then 2 else 1 end is_delete, ");
			sb.append("    case  fz.dr when 0 then 1 else 0 end is_enabled, ");
			sb.append("    case when oos.code='global' then '0001' else oos.code end agency_code, ");
			sb.append("    case when og.code is null then '0001' else og.code end acct_set_code ");
			sb.append(" from bd_accassitem fz ");
			sb.append("left join md_class mc on fz.classid = mc.id ");
			sb.append("left join org_orgs oos on fz.pk_org = oos.pk_org ");
			sb.append("left join org_group og on fz.pk_group  = og.pk_group ");
			sb.append("where (fz.dr = 0 or fz.dr is null) ");
			Object startdate = null;
			Object stopdate = null;
			Object type = keyMap.get("type");
			if("1".equals(type)) { //  [指定时间段拉取,1];[拉指定的一天,2];
				Object begindate = keyMap.get("begindate")  == null  ? ymd.format(new Date()) : keyMap.get("begindate") ;
				Object enddate = keyMap.get("enddate") == null  ? ymd.format(new Date()) : keyMap.get("enddate") ;
				startdate = begindate + " 00:00:00";
				stopdate = enddate + " 23:59:59";
			}else if("2".equals(type)) { // [拉指定的一天,2]
				Object begindate = keyMap.get("begindate") == null  ? ymd.format(new Date()) : keyMap.get("begindate") ;
				startdate = begindate + " 00:00:00";
				stopdate = begindate + " 23:59:59";
			}else { // [定时执行, ] 默认同步频率30分钟  
		        Calendar calendar = Calendar.getInstance();
		        stopdate = ymdsfm.format(calendar.getTime());//当前时间
		        Object synctime = keyMap.get("synctime"); //  同步频率
		        if(synctime ==  null ) {
			        calendar.add(Calendar.MINUTE, -30); // time 的前几分钟
		        }else {
	        		int time = Integer.parseInt(synctime.toString());
			        calendar.add(Calendar.MINUTE, -time); // time 的前几分钟
		        }
		        startdate = ymdsfm.format(calendar.getTime());
			}
//			sb.append(" and fz.ts between '"+startdate+"' and '"+stopdate+"' ");
//			sb.append(" and fz.code = '0019' ");
			return sb.toString();
		}
		return null;
	}
	
	/**
	 * 构建请求参数
	 * @return
	 * @throws Exception 
	 */
	public JSONArray buildParam(Map<String, Object> map,List<LogVO> listVOs) throws Exception{
		JSONArray jsonArray = new JSONArray();
		String year = ymd.format(new Date()).split("-")[0];
		String data_id = map.get("data_id")+year;
		String ELEMENT_CODE = "ACITEM";
		JSONObject json = new JSONObject();
		json.put("DATA_ID", data_id);  // 帐套唯一标识
		json.put("ELEMENT_CODE", map.get("element_code"));
		json.put("CODE", ToolUtils.getJudgeAttribute(map.get("element_code")));
		json.put("ELEMENT_NAME", ToolUtils.getJudgeAttribute(map.get("element_name")));
		json.put("NAME",ToolUtils.getJudgeAttribute(map.get("element_name")));
		json.put("MOF_DIV_CODE", super.getMOF_DIV_CODE()); // 财政区划代码
		json.put("ACCT_SET_CODE", super.getAccount()); // 账套类型
		json.put("AGENCY_CODE", super.getUnit()); //单位代码
		json.put("ACCT_SET_NAME", super.getACCT_SET_NAME());  // 账套名称
		json.put("AGENCY_NAME", super.getAGENCY_NAME()); // 单位名称
		json.put("SET_YEAR", year); //会计年度
		json.put("START_DATE", super.getYMD(year + "-01-01")); // 启用日期
		json.put("END_DATE", "20991231"); // 停用日期
		json.put("PARENT_CODE", ToolUtils.getJudgeAttribute(map.get("parent_code"))); // 父级节点代码
		json.put("LEVEL_NO", 1); // 级次
		json.put("IS_LEAF", 1); // 是否末级
		json.put("IS_DELETED",  map.get("is_delete"));
		json.put("UPDATE_TIME", super.getYMDHMS(String.valueOf(new UFDateTime()))); // 更新时间
		json.put("IS_ENABLED", map.get("is_enabled")); // 是否启用( 0 停用  1 启用 )
		json.put("VOU_AUX_CODE", ToolUtils.getJudgeAttribute(map.get("vou_aux_code"))); // 自定义辅助核算编码
		LogVO logVO = getDbService().buildLogVO(map, json, "financial", "assistHSYS");
		listVOs.add(logVO);
		jsonArray.add(json);
		return jsonArray;
	}
	
	/**
	 * 获取第三方同步地址
	 * @param initCode
	 * @return 
	 * @throws Exception
	 */
	public String getURL(String initCode) throws Exception{ 
		String url = InitParamUtils.getOrgParam("GLOBLE00000000000000",initCode)+"/pty/gla-dec/v1/account/accountclsitemdatas";
		getLog().info("----第三步接口请求地址:" + url);
		return url;
	}

	/**
	 * 数据库操作服务
	 * @return
	 */
	public IDBService getDbService() {
		if(dbService == null) {
			dbService = NCLocator.getInstance().lookup(IDBService.class);
		}
		return dbService;
	}

	public INCPushCZService getNcPushCZService() {
		if(null == this.ncPushCZService) {
			this.ncPushCZService = NCLocator.getInstance().lookup(INCPushCZService.class);
		}
		return this.ncPushCZService;
	}
	public BaseDAO getDao() {
		return dao == null ? new BaseDAO() : dao ;
	}
}
